var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    form_id: "",
    count: 3,
    name: "",
    phone: "",
    time: "2023-2-22",
    fileList: [],
    fileListVideo: [],
    lat: "",
    lng: "",
    loaction_title: "",
    detail: "",
    max_count: 1,
    form_cluster: [],
    title: "",
    imgUrl: "",
    description: "",
    popup_time: false,
    currentDate: new Date().getTime(),
    name_tips: "",
    phone_tips: "",
    openDateLw: false,
    address_title: "",
    provinceData: [],
    cityData: [],
    districtData: [],
    selectAddressData: [],
    pickerValue: [0, 0, 0],
  },
  // 收货地址滚动事件
  bindChange: function (e) {
    var val = e.detail.value;
    if (this.data.pickerValue[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
    }
    if (this.data.pickerValue[1] != val[1]) {
      val[2] = 0;
    }
    this.setData({
      "pickerValue[0]": val[0],
      "pickerValue[1]": val[1],
      "pickerValue[2]": val[2],
    });
    this._initAddressInfo();
  },

  select_area() {
    this.setData({
      openDateLw: true,
      'pickerValue[0]':24,
    })
    this._initAddressInfo();
    setTimeout(() => {
      this.setData({ 'pickerValue[1]':14})
      this._initAddressInfo();
    }, 300);
    console.log(this.data.pickerValue,"assaaaaaaaaaa");
  },
  _okAddress() {
    let seleData = this.data.selectAddressData;
    this.setData({
      "address_title": seleData[0].name + "-" + seleData[1].name + "-" + seleData[2].name,
    });
    this._closeDateLw();
  },
  // 关闭选择收货地址
  _closeDateLw() {
    this.setData({
      openDateLw: false,
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options, "options====");
    let date = new Date();
    let year = date.getFullYear(),
      month = date.getMonth() + 1,
      day = date.getDate();
    let time = `${year}-${month}-${day}`;
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      if (scene) {
        let info_arr = [];
        info_arr = scene.split(',');
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split('=');
          if (chil_arr[0] == 'mid') {
            this._setMid(chil_arr[1]);
          }
          if (chil_arr[0] == 'form_id') {
            this.setData({form_id:chil_arr[1]})
          }
        }
      }
    }else{
      this.setData({form_id: options.form_id || '',})
    }
    this.setData({time})
    this.getData();
    if (wx.getStorageSync('random_shot_json')) {
      let json = wx.getStorageSync('random_shot_json');
      this.setData({
        name: json.name,
        phone: json.mobile,
        message: json.rows,
        fileList: json.images,
        fileListVideo: json.videos,
        address_title:json.area,
      })
    }
    if (wx.getStorageSync('address-point')) {
      let {
        lat,
        lng
      } = wx.getStorageSync('address-point').point;
      this.setData({lat,lng})
      this.getAmap(lat, lng);
    }
        //加载地址数据初始化
        this._initAddressInfo();
  },
   //地址选择器数据初始化
   _initAddressInfo: function () {
    var that = this;
    var _keyName = "provinceData";
    wx.getStorage({
      key: _keyName,
      success: function () {
        that._getProvinceData();
      },
      fail: function (res) {
        app._getNetWork({
          url: app.getNetAddresss("member.member-address.address"),
          success: function (res) {
            var response = res.data;
            var province = response.data.province;
            var city = response.data.city;
            var district = response.data.district;
            wx.setStorage({
              key: "provinceData",
              data: province,
            });
            wx.setStorage({
              key: "cityData",
              data: city,
            });
            wx.setStorage({
              key: "districtData",
              data: district,
            });
            that._initAddressInfo();
          },
          fail: function (res) {},
          state: true,
        });
      },
    });
  },
    // 读取省key
    _getProvinceData () {
      wx.getStorage({
        key: "provinceData",
        success:res=> {
          this.setData({
            provinceData: res.data,
          });
          this.setData({
            "selectAddressData[0].name": res.data[this.data.pickerValue[0]].areaname,
            "selectAddressData[0].id": res.data[this.data.pickerValue[0]].id,
            "selectAddressData[0].index": this.data.pickerValue[0],
          });
          this._getCityData();
        },
      });
    },
    // 读取城市key，筛选城市data
    _getCityData: function () {
      var _data = this.data.selectAddressData[0];
      var that = this;
      var _keyName = "cityData";
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          var _json = [];
          for (var i = 0; i < res.data.length; i++) {
            if (res.data[i].parentid == _data.id) {
              _json.push(res.data[i]);
            }
          }
          that.setData({
            cityData: _json,
          });
          that.setData({
            "selectAddressData[1].name": _json[that.data.pickerValue[1]].areaname,
            "selectAddressData[1].id": _json[that.data.pickerValue[1]].id,
            "selectAddressData[1].index": that.data.pickerValue[1],
          });
          that._getDistrictData();
        },
      });
    },
    // 读取地区key，筛选地区data
    _getDistrictData: function () {
      var _data = this.data.selectAddressData[1];
      var that = this;
      var _keyName = "districtData";
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          var _json = [];
          for (var i = 0; i < res.data.length; i++) {
            if (res.data[i].parentid == _data.id) {
              _json.push(res.data[i]);
            }
          }
          that.setData({
            districtData: _json,
          });
          that.setData({
            "selectAddressData[2].name": _json[that.data.pickerValue[2]].areaname,
            "selectAddressData[2].id": _json[that.data.pickerValue[2]].id,
            "selectAddressData[2].index": that.data.pickerValue[2],
          });
        },
      });
    },
  time_confirm(e) {
    let date = new Date(e.detail);
    let year = date.getFullYear(),
      month = date.getMonth() + 1,
      day = date.getDate();
    let time = `${year}-${month}-${day}`;
    this.setData({
      time
    })
    this.onClose();
  },
  onClose() {
    this.setData({
      popup_time: false
    })
  },
  getData() {
    app._getNetWork({
      url: app.getNetAddresss('plugin.shoot-casually.frontend.form.show'),
      data: {
        form_id: this.data.form_id
      },
      success: resdata => {
        let {
          result,
          data,
          msg
        } = resdata.data;
        if (result) {
          let name_tips = data.form_cluster[0].tips.split("：")[1];
          let phone_tips = data.form_cluster[1].tips.split("：")[1];
          
          let _detail  = data.detail.replace(/<p([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig, '<p')
          .replace(/<p>/ig, '<p style="font-size: 15px; line-height: 25px;">')
          .replace(/<img([\s\w"-=\/\.:;]+)((?:(height="[^"]+")))/ig, '<img$1')
          .replace(/<img([\s\w"-=\/\.:;]+)((?:(width="[^"]+")))/ig, '<img$1')
          .replace(/<img([\s\w"-=\/\.:;]+)((?:(style="[^"]+")))/ig, '<img$1')
          .replace(/<img([\s\w"-=\/\.:;]+)((?:(alt="[^"]+")))/ig, '<img$1')
          .replace(/<img([\s\w"-=\/\.:;]+)/ig, '<img style="width: 100%;height:100%" $1');
          this.setData({
            description: data.description,
            imgUrl: data.imgUrl,
            title: data.title,
            form_cluster: data.form_cluster,
            max_count: data.form_cluster[6].count,
            detail: _detail,
            name_tips,
            phone_tips
          })
      
          console.log(_detail,"_detail====");

          wx.setNavigationBarTitle({
            title: data.title,
          })
        } else {
          app.tips(msg);
        }
      }
    })
  },
  afterRead(event) {
    wx.showLoading({
      title: '上传中'
    })
    const {
      file
    } = event.detail;
    let urlStr = app.getNetAddresss("upload.uploadPic");
    wx.uploadFile({
      url: urlStr,
      filePath: file[0].url,
      name: 'file',
      success: (resdata) => {
        app.tips("上传成功")
        let res = JSON.parse(resdata.data);
        this.data.fileList.push({
          ...file,
          url: res.data.img_url,
          status: "done",
          message: '上传完成'
        });
        this.setData({
          fileList: this.data.fileList
        });
      },
      fail(err) {
        app.tips("上传失败")
        console.log(err);
      },
      complete() {
        wx.hideLoading();
      }

    });
  },
  onanotherPicsdVideo() {
    wx.chooseMedia({
      count: 3, //上传视频的个数
      mediaType: ['video'], //限制上传的类型为video
      sourceType: ['album', 'camera'], //视频选择来源
      maxDuration: 60, //拍摄限制时间
      camera: 'back', //采用后置摄像头
      success: (res) => {
        console.log(res.tempFiles);
        //获取临时存放的视频资源
        // let tempFilePath = res.tempFiles[0].tempFilePath
        let tempFiles = res.tempFiles;
        //获取该视频的播放时间
        let duration = res.tempFiles[0].duration
        console.log("视频播放时间为" + duration)
        //获取视频的大小(MB单位)
        let size = parseFloat(res.tempFiles[0].size / 1024 / 1024).toFixed(1)
        console.log("视频大小为" + size)
        //获取视频的高度
        let height = res.tempFiles[0].height
        console.log("视频高度为" + height)
        //获取视频的宽度
        let width = res.tempFiles[0].width
        console.log("视频宽度为" + width)
        //校验大小后，符合进行上传
        if (size > 20) {
          let beyongSize = size - 20 //获取视频超出限制大小的数量
          Toast("上传的视频大小超限,超出" + beyongSize + "MB,请重新上传！")
          return
        } else {
          //符合大小限制，进行上传
          console.log("开始上传！！！",tempFiles.length)
          if(tempFiles&&tempFiles.length==1){
            console.log("一===");
            this.upload_file(tempFiles[0].tempFilePath);
          }else{
            console.log("===qqqqq");
            tempFiles.forEach(item=>{
              this.upload_file(item.tempFilePath);
            })
          }
        }
      },
    })
  },
  upload_file(filePath){
    let urlStr = app.getNetAddresss("upload.uploadPic");
    urlStr += '&upload_type=video';
    wx.uploadFile({
      url: urlStr,
      filePath,
      name: 'file',
      success: (resdata) => {
        app.tips("上传成功")
        let _res = JSON.parse(resdata.data);
        console.log(_res, "res===");
        this.data.fileListVideo.push(_res.data.img_url);
        this.setData({
          fileListVideo: this.data.fileListVideo
        });
      },
      fail(err) {
        app.tips("上传失败")
        console.log(err);
      },
      complete() {
        wx.hideLoading();
      }

    });
  },

  afterReadVideo(event) {
    let {
      file
    } = event.detail;
    wx.showLoading({
      title: '上传中'
    })
    console.log(file, "=====");
    let urlStr = app.getNetAddresss("upload.uploadPic");
    urlStr += '&upload_type=video';
    wx.uploadFile({
      url: urlStr,
      filePath: file[0].url,
      name: 'file',
      success: (resdata) => {
        app.tips("上传成功")
        let res = JSON.parse(resdata.data);
        console.log(res, "res===");
        this.data.fileListVideo.push(res.data.img_url);
        this.setData({
          fileListVideo: this.data.fileListVideo
        });
      },
      fail(err) {
        app.tips("上传失败")
        console.log(err);
      },
      complete() {
        wx.hideLoading();
      }

    });
  },
  del(e) {
    let index = e.currentTarget.dataset.index;
    this.data.fileListVideo.splice(index, 1);
    this.setData({
      fileListVideo: this.data.fileListVideo
    });
  },
  del_photo(e) {
    let index = e.currentTarget.dataset.index;
    this.data.fileList.splice(index, 1);
    this.setData({
      fileList: this.data.fileList
    });

  },
  submit() {
    let json = {
      form_id: this.data.form_id,
      name: this.data.name,
      mobile: this.data.phone,
      date: this.data.time,
      area: this.data.address_title,
      rows: this.data.message,
      images: this.data.fileList,
      videos: this.data.fileListVideo,
      coordinate: {
        longitude: this.data.lng,
        latitude: this.data.lat,
        address: this.data.loaction_title,
      }
    }

    if (this.data.form_cluster[1].required && !this.data.phone) {
      return app.tips('请输入' + this.data.form_cluster[1].title);
    } else if (this.data.form_cluster[5].required && !this.data.message) {
      return app.tips('请输入' + this.data.form_cluster[5].title);
    } else if (this.data.form_cluster[7].required && this.data.fileListVideo.length == 0) {
      return app.tips('请上传' + this.data.form_cluster[7].title);
    } else if (this.data.form_cluster[6].required && this.data.images.length == 0) {
      return app.tips('请上传' + this.data.form_cluster[6].title);
    } else if (this.data.form_cluster[4].required && !this.data.time) {
      return app.tips('请选择' + this.data.form_cluster[4].title);
    } else if (this.data.form_cluster[3].required && !this.data.locationTitle) {
      return app.tips('请选择' + this.data.form_cluster[3].title);
    } else if (this.data.form_cluster[0].required && !this.data.name) {
      return app.tips('请输入' + this.data.form_cluster[0].title);
    } else if (this.data.form_cluster[2].required && !this.data.address_title) {
      return app.tips('请选择' + this.data.form_cluster[2].title);
    }

    app._postNetWork({
      url: app.getNetAddresss("plugin.shoot-casually.frontend.form-member.submit"),
      data: json,
      success: resdata => {
        let {
          result,
          msg
        } = resdata.data;
        app.tips(msg);
        if (result) {
          wx.removeStorageSync('random_shot_json');
          wx.reLaunch({
            url: '/packageJ/random_shot/list/list',
          })
        }
      }
    })

  },
  onChangeText(e) {
    this.setData({
      message: e.detail
    });
  },
  onanotherPics() {
    let that = this;
    let ig = '2';
    wx.chooseImage({
      count: this.data.max_count,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // var tempFilePaths = res.tempFilePaths
        that.unload({
          tempFilePaths: res.tempFilePaths
        }, ig);
      }
    });
  },
  unload(data, ig) {
    console.log(ig);
    let urlStr = app.getNetAddresss('upload.uploadPic');
    let that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: urlStr,
      filePath: data.tempFilePaths[i],
      name: 'file',
      formData: null,
      success(resdata) {
        var res = JSON.parse(resdata.data);
        app.tips("上传成功")
        if (ig == '1') {
          that.data.fileList.push(res.data.img_url);
          that.setData({
            fileList: that.data.fileList
          });
        } else if (ig == 2) {
          that.data.fileList.push(res.data.img_url);
          that.setData({
            fileList: that.data.fileList
          });
        }
        console.log(that.data.fileList);
      },
      fail(e) {
        fail++;
      },
      complete(e) {
        i++;
        if (i == data.tempFilePaths.length) { //当图片传完时，停止调用
        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.unload(data, ig); //递归，回调自己
        }
      }
    });
  },
  show_popup() {
    this.setData({
      popup_time: true
    })
  },
  onChangeMobile(e) {
    this.setData({
      phone: e.detail
    });
  },
  onChange(e) {
    this.setData({
      name: e.detail
    });
  },
  select_location() {
    let json = {
      form_id: this.data.form_id,
      name: this.data.name,
      mobile: this.data.phone,
      date: this.data.time,
      area: this.data.address_title,
      rows: this.data.message,
      images: this.data.fileList,
      videos: this.data.fileListVideo,
      coordinate: {
        longitude: this.data.lng,
        latitude: this.data.lat,
        address: this.data.loaction_title,
      }
    }
    wx.setStorageSync('random_shot_json', json)
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const url = `/${currentPage.route}?form_id=${this.data.form_id}`;
    console.log(url, "url===");
    wx.setStorageSync('diyurl', url)
    wx.navigateTo({
      url: '/packageC/o2o/o2oLocation_loc/o2oLocation_loc?tag=shop',
    })
  },
  getAmap(latitude, longitude) {
    app.getReverseGeocoder(latitude, longitude).then(res => {
      console.log("userLocationFlag", res);
      this.setData({
        "loaction_title": `${res.address_component.province}${res.address_component.city}${res.formatted_addresses.recommend}`
      })
    }).catch(function (err) {
      console.log(err);
    });
  },
     //长按图片扫描二维码
     scan(){
      let imgs = []
      this.data.detail.replace(/}*src=[\'"]([^\'"]+)[^>]*>/gi, function (match, capture) {
        imgs.push(capture);
      })
       wx.previewImage({
        urls:imgs
      })
    },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (this.data.title || this.data.imgUrl) {

      return {
        path: `/packageJ/random_shot/index/index?form_id=${this.data.form_id}`,
        title: this.data.title,
        imageUrl: this.data.imgUrl,
      }
    };
  },
  onShareTimeline: function () {

  }
});